#include "testMutex.hpp"

using namespace MutexModel;

// 全局变量
int count = 1000; // 总计共1000张票

// 线程类
class threadData
{
public:
    // 构造函数
    threadData(const std::string &name, Mutex &lock)
        : _name(name),
          _lock(&lock)
    {
    }

    // 析构函数
    ~threadData() {}

    // private:
    std::string _name;      // 线程名称
    Mutex *_lock; // 互斥锁
};

// 线程函数
void *route(void *arg)
{
    threadData *td = (threadData *)arg;
    while (1)
    {
        // 上锁
       //pthread_mutex_lock(td->_lock);
       //td->_lock->lock(); 
       LockGuard LG(*td->_lock);  
       if (count > 0)
        {
            usleep(1000);
            // std::cout<< " 线程ID: "<< arg << " 剩余票数：" << count << std::endl;
            printf(" 线程ID: %s 剩余票数：%d\n", td->_name.c_str(), count);
            count--;

            // 解锁
            //pthread_mutex_unlock(td->_lock);
            //td->_lock->unlock();
        }
        else
        {
            // 解锁
            //pthread_mutex_unlock(td->_lock);
            //td->_lock->unlock();
            
            break;
        }
    }
    return nullptr;
}

int main()
{
    // 创建互斥锁
    /* pthread_mutex_t lock;
    pthread_mutex_init(&lock, NULL); */
    Mutex lock;

    // 创建四个线程
    pthread_t t1, t2, t3, t4;

    // 构造四个线程
    threadData *data1 = new threadData("thread - 1", lock);
    threadData *data2 = new threadData("thread - 2", lock);
    threadData *data3 = new threadData("thread - 3", lock);
    threadData *data4 = new threadData("thread - 4", lock);

    // 启动四个线程
    pthread_create(&t1, NULL, route, (void *)data1);
    pthread_create(&t2, NULL, route, (void *)data2);
    pthread_create(&t3, NULL, route, (void *)data3);
    pthread_create(&t4, NULL, route, (void *)data4);

    // 等待所有线程结束
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);

    // 销毁互斥锁
    //pthread_mutex_destroy(&lock);

    return 0;
}